package io.renren.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import io.renren.service.StsTokenService;
import io.renren.vo.StsTokenVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class StsTokenServiceImpl implements StsTokenService {
    @Value("${aliyun.sts.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.sts.secret}")
    private String secret;
    @Value("${aliyun.sts.roleArn}")
    private String roleArn;
    @Value("${aliyun.sts.roleSessionName}")
    private String roleSessionName;
    @Value("${aliyun.sts.endpoint}")
    private String endpoint;
    /**
     * token失效时间，单位秒(不设置默认60封装,这里设置15分钟)
     */
    private static final Long durationSeconds = 60*15L;

    @Override
    public StsTokenVO getStsToken() {
        StsTokenVO tokenVO = new StsTokenVO();
        try {
            // 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
            DefaultProfile.addEndpoint("cn-hangzhou","Sts",endpoint);
            // 构造default profile（参数留空，无需添加region ID）
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, secret);
            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            AssumeRoleRequest request = new AssumeRoleRequest();
            request.setSysMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setDurationSeconds(durationSeconds);
            // 针对该临时权限可以根据该属性赋予规则，格式为json，没有特殊要求，默认为空
            // request.setPolicy(policy); // Optional
            AssumeRoleResponse response = client.getAcsResponse(request);
            AssumeRoleResponse.Credentials credentials = response.getCredentials();
            tokenVO.setAccessKeyId(credentials.getAccessKeyId());
            tokenVO.setSecretAccessKey(credentials.getAccessKeySecret());
            tokenVO.setSecurityToken(credentials.getSecurityToken());
            return tokenVO;
        } catch (Exception e) {
            return null;
        }
    }
}
